package com.ai;

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.swing.text.html.parser.DocumentParser;

import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.parser.TextDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentByLineSplitter;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class AiApplication {

    public static void main(String[] args) {
        SpringApplication.run(AiApplication.class, args);
    }


    /**
     * 知识库向量化，存储知识库向量
     *
     * @param qwenEmbeddingModel
     * @param embeddingStore
     * @return
     * @throws URISyntaxException
     */
    @Bean
    public CommandLineRunner ingestTermOfServiceToVectorStore(QwenEmbeddingModel qwenEmbeddingModel,
                                                              EmbeddingStore<TextSegment> embeddingStore) throws URISyntaxException {
        Path path = Paths.get(AiApplication.class.getClassLoader().getResource("rag/terms-of-service.txt").toURI());

        return args -> {
            TextDocumentParser documentParser = new TextDocumentParser();
            Document document = FileSystemDocumentLoader.loadDocument(path, documentParser);

            DocumentByLineSplitter splitter = new DocumentByLineSplitter(
                    500,
                    200
            );

            List<TextSegment> segments = splitter.split(document);

            List<Embedding> embeddings = qwenEmbeddingModel.embedAll(segments).content();
            embeddingStore.addAll(embeddings, segments);
        };
    }
}
